package com.cango.framework.base.util;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapUtils {
    private static final Log log = LogFactory.getLog(MapUtils.class);

    public static Map<String, Object> convertToMap(Object obj) {
        if (null == obj) {
            return null;
        }
        if (obj instanceof Map) {
            return (Map<String, Object>) obj;
        }
        Map<String, Object> returnMap = new HashMap<>();
        try {
            returnMap = convertBeanToMap(obj);

        } catch (Exception e) {
            log.warn("convert object failed", e);
        }
        return returnMap;
    }

    public static Map<String, Object> convertBeanToMap(Object bean) throws Exception {
        if (null == bean) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        PropertyUtilsBean propUtilsBean = BeanUtilsBean.getInstance().getPropertyUtils();
        PropertyDescriptor[] descriptors = propUtilsBean.getPropertyDescriptors(bean);
        for (PropertyDescriptor descriptor : descriptors) {
            String name = descriptor.getName();
            if ("class".equals(name)) {
                continue;
            }
            Method method = propUtilsBean.getReadMethod(descriptor);
            if (method != null) {
                Object value = method.invoke(bean);
                if (value != null) {
                    map.put(name, value);
                }
            }
        }
        return map;
    }

    /**
     * <p>Description: 拷贝集合</p>
     * @auth wzx
     *
     * @param src 源
     * @return 集合
     * @throws IOException IO异常
     * @throws ClassNotFoundException 类转换异常
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        List<T> dest = (List<T>) in.readObject();
        return dest;
    }

}
